<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="特征类型">
            <el-select v-model="form.type" placeholder="请选择特征类型">
              <el-option
                v-for="dict in dict.type.feature_extraction_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="分析数据">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :http-request="uploadHttpRequest"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="uploadFiles"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持csv/mat格式文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">下载</el-button>
        <el-button @click="resetQuery">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {getPdf} from "../../../api/bearing/signal";
  import {FeatureExtraction} from "../../../api/bearing/feature";

  export default {
    name: "Extraction",
    dicts: ['feature_extraction_type'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        Data: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 数据集表格数据
        datasetList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        fileList: [],
        signalAnalysisType1: true,
        signalAnalysisType2: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          filtering: null,
          name: null,
          datasetName: null,
          conditionName: null,
          bearingName: null,
        },
        csvData: [],
        workbook: {},
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      }
    }
    ,
    /**
     * 数据发生改变
     */

    watch: {}
    ,

    /**
     * 创建完毕
     */

    created() {
      this.$nextTick(() => {
        //this.getdata()
      })
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 查询所有元器件信息
      getList() {
        let formData = new FormData();
        if ("undefined" === typeof (this.form.type)) {
          this.$modal.msgError("请选择特征类型");
          return;
        }
        if ("undefined" === typeof (this.form.files)) {
          this.$modal.msgError("请上传信号分析文件");
          return;
        }
        formData.append('files', this.form.files[0].raw);
        for (let key in this.form) {
          if (key !== "files") {
            formData.append(key, this.form[key])
          }
        }
        formData.append('type', this.form.type);
        this.loading = true;
        FeatureExtraction(formData)
          .then(res => {
            const blob = new Blob([res], {type: 'application/csv'});
            const url = URL.createObjectURL(blob);
            let anchor = document.createElement("a");
            //设置下载的文件名
            anchor.download = `features_${new Date().getTime()}.csv`;
            anchor.href = url;
            anchor.click();
          });
        this.loading = false;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploadHttpRequest(data) {
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      uploadFiles(item, fileList) {
        this.form.files = fileList
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.form.type = null;
        this.fileList = [];
        this.form.files = undefined;
        this.loading = true;
        this.Data = [];
        this.loading = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.bid);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      changeAnalysisType1(type) {
        this.signalAnalysisType2 = !type
      },
      changeAnalysisType2(type) {
        this.signalAnalysisType1 = !type
      },
      downloadPdf() {
        getPdf().then(response => {
          // 创建一个新的Blob对象来表示响应数据
          const blob = new Blob([response], {type: 'application/pdf'});
          // 创建一个临时URL来表示这个Blob对象
          const url = URL.createObjectURL(blob);
          // 新增代码：在新窗口中预览PDF文件
          const previewWindow = window.open(url);
          // 新增代码：在新窗口中添加一个下载按钮
          previewWindow.onload = () => {
            const downloadButton = previewWindow.document.createElement("button");
            downloadButton.innerText = "Download";
            // 当用户点击下载按钮时，创建一个<a>元素并设置其href属性为临时URL
            downloadButton.onclick = () => {
              const link = document.createElement("a");
              link.href = url;
              // 设置download属性以便在用户点击链接时下载文件并将其保存为'signalAnalysisResult.pdf'
              link.download = 'signalAnalysisResult.pdf';
              // 将链接添加到文档中
              document.body.appendChild(link);
              // 模拟点击链接以下载PDF文件
              link.click();
            };
            // 将下载按钮添加到新窗口中
            previewWindow.document.body.appendChild(downloadButton);
          }
        })
      }
    }
  }
</script>
